package com.xiguaji.tiktok.v1.ins.product.service;

import cn.hutool.core.date.DateUtil;
import com.xiguaji.boot.toolkit.elasticsearch.RestClientHelper;
import com.xiguaji.boot.toolkit.jdbc.Page;
import com.xiguaji.tiktok.config.Config;
import com.xiguaji.tiktok.utils.ESUtil;
import com.xiguaji.tiktok.v1.ins.blogger.model.InsBlogger;
import com.xiguaji.tiktok.v1.ins.blogger.repository.InsBloggerRepository;
import com.xiguaji.tiktok.v1.ins.product.dto.*;
import com.xiguaji.tiktok.v1.ins.product.repository.InsProductRepository;
import io.micrometer.core.instrument.util.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class InsProductService {
    @Autowired
    InsBloggerRepository insBloggerRepository;

    @Autowired
    InsProductRepository insProductRepository;

    @Autowired
    Config config;

    private final int PRODUCT_TOTAL_SIZE = 1000;

    private final int [] days = new int []{7,15,30};

    public Page<InsProductData> getPage(InsProductSearchRequest insProductRequest) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // 时间区间
        long timeRang = System.currentTimeMillis() / 1000 - config.getLatestDays() * 24 * 3600;
        boolQueryBuilder.must(QueryBuilders.rangeQuery("lastMediaTagTime").gte(timeRang));

        if(StringUtils.isNotEmpty(insProductRequest.getName())){
            boolQueryBuilder.must(QueryBuilders.wildcardQuery("productName","*"+insProductRequest.getName()+"*"));
        }

        if(StringUtils.isNotEmpty(insProductRequest.getCategory())){
            boolQueryBuilder.must(QueryBuilders.termQuery("overallCategoryName",insProductRequest.getCategory()));
        }

        String sort;
        switch (insProductRequest.getSort()){
            case 1:
                sort = "mediaCount";
                break;
            case 2:
                sort = "tec";
                break;
            default:
                sort = "influencerCount";
        }
        Page<InsProductData> insProductDataPage = RestClientHelper.page(InsProductData.class, ESUtil.INS_PRODUCT_INDEX, boolQueryBuilder,insProductRequest.getPage(),insProductRequest.getPageSize(),PRODUCT_TOTAL_SIZE,sort, SortOrder.DESC);

        insProductDataPage.getList().forEach(insAdMediaListData -> {
            Optional<InsBlogger> insBloggerOptional = insBloggerRepository.findByUid(insAdMediaListData.getMerchantUid());
            if(insBloggerOptional.isPresent()){
                insAdMediaListData.setUsername(insBloggerOptional.get().getUsername());
                insAdMediaListData.setFullName(insBloggerOptional.get().getFullName());
                insAdMediaListData.setPicUrl(insBloggerOptional.get().getPicUrl());
                insAdMediaListData.setVerified(insBloggerOptional.get().getIsVerified());
            }
        });
        return insProductDataPage;
    }

    /**
     * 获取商品基础信息
     * @param productId
     * @return
     */
    public InsProductData getProductByProductId(long productId){
        return insProductRepository.findByProductDataByProductId(productId);
    }

    /**
     * 获取产品统计信息
     * @param productId
     * @param dayType
     * @return
     */
    public InsProductStatistics getProductStatistics(long productId,int dayType){
        Long [] times = lastStTime(productId,dayType);
        return insProductRepository.getInsMediaProductDataCountByTakenTime(productId,times[0],times[1]);
    }

    /**
     * 该产品的博主走趋
     * @param productId
     * @param dayType
     * @return
     */
    public List<InsProductTrend> getBloggerTrend(long productId, int dayType){
        Long [] times = lastStTime(productId,dayType);
        return insProductRepository.getProductBloggerCount(productId,times[0],times[1]);
    }

    /**
     * 该产品的帖子走趋
     * @param productId
     * @param dayType
     * @return
     */
    public List<InsProductTrend> getMediaTrend(long productId, int dayType){
        Long [] times = lastStTime(productId,dayType);
        return insProductRepository.getProductMediaCount(productId,times[0],times[1]);
    }


    /**
     * 发布该商品的博主
     * @param productId
     * @param page
     * @param pageSize
     * @return
     */
    public Page<InsProductBloggerData> getProductMediaBlogger(long productId, int page, int pageSize,int dayType){
        Long [] times = lastStTime(productId,dayType);
        return insProductRepository.getProductMediaBlogger(productId,page,pageSize, times[0],times[1]);
    }

    /**
     * 发布该商品的贴子
     * @param productId
     * @param page
     * @param pageSize
     * @param mediaType
     * @return
     */
    public Page<InsProductMedia> getProductMediaData(long productId,Long uid, int page, int pageSize,Integer mediaType,int dayType){
        Long [] times = lastStTime(productId,dayType);
        return insProductRepository.getProductMediaData(productId,uid,page,pageSize,mediaType, times[0],times[1]);
    }

    public Page<InsProductMedia> getProductMediaForNowData(long productId,Long uid, int page, int pageSize,Integer mediaType,int dayType){
        return insProductRepository.getProductMediaData(productId,uid,page,pageSize,mediaType, DateUtil.offsetDay(new Date(),-days[dayType]).getTime()/1000,DateUtil.currentSeconds());
    }

    /**
     * 获取博主下的所有商品
     * @param uid
     * @param page
     * @param pageSize
     * @param category
     * @return
     */
    public Page<InsProductData> getProductDataByUid(long uid, int page, int pageSize,String category,int dayType){
        return insProductRepository.getProductDataByUid(uid,page,pageSize,DateUtil.offsetDay(new Date(),-days[dayType]).getTime()/1000,DateUtil.currentSeconds(),category);
    }

    /**
     * 统计博主下分类的商品数量
     */
    public List<InsProductCategoryStatistics> getCountCategory(long uid,int dayType){
        List<InsProductCategoryStatistics> insProductCategoryStatistics = insProductRepository.getCountCategory(uid,DateUtil.offsetDay(new Date(),-days[dayType]).getTime()/1000,DateUtil.currentSeconds());
        int allCount = 0;
        for (InsProductCategoryStatistics insProductCategoryStatistic : insProductCategoryStatistics) {
            allCount +=insProductCategoryStatistic.getCount();
        }
        if(allCount > 0){
            InsProductCategoryStatistics insProductCategoryStatistic = new InsProductCategoryStatistics();
            insProductCategoryStatistic.setCategory("ALL");
            insProductCategoryStatistic.setCount(allCount);
            insProductCategoryStatistics.add(0,insProductCategoryStatistic);
        }

        insProductCategoryStatistics.removeIf(i ->StringUtils.isEmpty(i.getCategory()));

        return insProductCategoryStatistics;
    }

    public Page<InsProductData> getProductByMediaShortCode(String shortCode,int page,int pageSize){
        return insProductRepository.getPageProductDataByShortCode(shortCode,page,pageSize);
    }

    public Long getLastStTime(long productId){
        return insProductRepository.getLastStTime(productId);
    }

    private Long [] lastStTime(long productId,int dayType) {
        Long endTime = getLastStTime(productId);
        if(null == endTime || 0 == endTime){
            endTime = DateUtil.currentSeconds();
        }
        Long startTime = endTime - days[dayType]*24*3600;
        Long [] times = new Long[]{startTime,endTime};
        return times;
    }

}
